package cn.edu.sjtu.se.dslab.component.dp.parse;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;

import cn.edu.sjtu.se.dslab.util.FileUtil;


public class DesignPatternInstanceXMLGenerator {

	private static final String DEISNG_PATTERN_INSTANCE = "design-pattern-instance";
	private XMLWriter writer;
	private DesignPatternInstanceBean dpiBean;

	private Document document;

	public DesignPatternInstanceXMLGenerator(String relativePath, DesignPatternInstanceBean dpiBean) {
		this.dpiBean = dpiBean;
		File xmlFile = new File( FileUtil.getRootPath() + relativePath);
		System.out.println(FileUtil.getRootPath() + relativePath);
		try {
			if(!xmlFile.exists()){
				xmlFile.createNewFile();
			}
			writer = new XMLWriter(new FileWriter(xmlFile));
		}catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void generate(){
		document = DocumentHelper.createDocument();
		Element rootElement = document.addElement(DEISNG_PATTERN_INSTANCE);
		rootElement.addElement(DesignPatternInstanceBean.NAME).setText(dpiBean.getName());
		rootElement.addElement(DesignPatternInstanceBean.TYPE).setText(dpiBean.getType().toString());
		rootElement.addElement(DesignPatternInstanceBean.MAX_ID).setText(String.valueOf(dpiBean.getMaxId()));
		Element instancesElement = rootElement.addElement(DesignPatternInstanceBean.INSTANCES);
		for (Map<String,Property> instance : dpiBean.getInstances()){
			addInstance(instancesElement, instance);
		}

		try {
			writer.write(document);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if (writer != null){
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
	}

	private void addInstance(Element instancesElement, Map<String, Property> instance) {
		Element instanceElement = instancesElement.addElement(DesignPatternInstanceBean.INSTANCE);
		for (Property p: instance.values()){
			addProperty(instanceElement, p);
		}
	}

	private void addProperty(Element instanceElement, Property p) {
		Element pElement = instanceElement.addElement("property");
		pElement.addElement("name").setText(p.getName());
		pElement.addElement("value").setText(p.getValue());
	}



}
